package service

import (
	"github.com/go-resty/resty/v2"
	"github.com/pkg/errors"
	"github.com/spf13/cast"
	"time"
	"zsc-boot/app/customer/model"
	"zsc-boot/app/customer/model/response"
	"zsc-boot/core"
	"zsc-boot/core/orm"
)

type CustomerChannel struct {
	C *resty.Client
}

// PullSk 对接数客营销
func (c *CustomerChannel) PullSk() error {
	uuidList := []string{"3c7e6b12-45d1-4ece-8d24-7f273b911073"}
	var channelList []model.CustomerChannel
	if err := orm.GetDb().Where("uuid in (?) and status = ?", uuidList, true).Find(&channelList).Error; err != nil {
		return err
	}

	//获取机器人信息
	for _, channel := range channelList {
		var jqrRes response.YtJqrRes
		if _, err := c.getClient().SetResult(&jqrRes).SetFormData(map[string]string{
			"token": channel.SecretKey,
		}).Post(channel.Remark + "?r=authorization-check/token-check"); err != nil {
			return err
		}
		if jqrRes.StatusCode != 1 {
			return errors.New("获取机器人id异常" + jqrRes.Message)
		}

		for _, jqr := range jqrRes.Info {
			var ytPhoneRes response.YtPhoneRes
			reqType := "today"
			if time.Now().Format(time.TimeOnly) == "00:05:00" {
				reqType = "history"
			}

			res, _ := c.getClient().SetResult(&ytPhoneRes).SetFormData(map[string]string{
				"token":      channel.SecretKey,
				"asrid":      jqr.Id,
				"type":       reqType,
				"start_time": time.Now().Add(-time.Minute * 10).Format(time.DateTime),
				"end_time":   time.Now().Format(time.DateTime),
				"page":       "1",
				"page_size":  "10000",
			}).Post(channel.Remark + "?r=authorization-check/get-call-records")
			core.GetLogger().Warn("拉回来了")
			core.GetLogger().Warn(res.Request.FormData.Encode())
			core.GetLogger().Warn(string(res.Body()))

			if jqrRes.StatusCode != 1 {
				return errors.New("获取客户列表异常" + string(res.Body()))
			}
			for _, customerInfo := range ytPhoneRes.Info.Info {
				if len(customerInfo.CustomerId) < 2 || cast.ToInt(customerInfo.Scores) < 60 {
					continue
				}

				createData := model.CustomerImportLog{
					ChannelId:    channel.ID,
					ChannelName:  channel.Name,
					Name:         customerInfo.Name,
					Mobile:       customerInfo.Dst,
					Remark:       customerInfo.ToRemark(),
					IsRepeated:   false,
					IsAllocation: false,
					Tag:          customerInfo.ToTag(),
				}

				//判断是否重复
				var oldData model.CustomerImportLog
				if err := orm.GetDb().Where("mobile = ?", customerInfo.Dst).Find(&oldData).Error; err != nil {
					return err
				}
				if oldData.ID != 0 {
					createData.IsRepeated = true
				}
				if err := orm.Create[model.CustomerImportLog](createData); err != nil {
					return err
				}
			}

		}
	}
	return nil
}

func (c *CustomerChannel) CallBack() error {
	nameList := []string{"抖音Y", "腾讯Y"}
	var channelList []model.CustomerChannel
	if err := orm.GetDb().Where("name in (?)", nameList).Find(&channelList).Error; err != nil {
		return err
	}
	channelIds := make([]uint, 0, len(nameList))
	for _, v := range channelList {
		channelIds = append(channelIds, v.ID)
	}
	var customerList []model.Customer
	if err := orm.GetDb().Where("channel_id in (?) and updated_at > ? ",
		channelIds, time.Now().Add(-time.Hour*24*30).Format(time.DateTime)).Find(&customerList).Error; err != nil {
		return err
	}

	for _, v := range customerList {
		data := map[string]string{
			"phone": v.Mobile,
			"level": cast.ToString(v.Level),
		}
		if v.FollowStatus == "已签约" {
			data["status"] = "10"
		} else if v.FollowStatus == "已加微信" {
			data["status"] = "4"
		} else if v.FollowStatus == "有意向" {
			data["status"] = "5"
		}

		res, err := c.getClient().SetFormData(data).Post("http://api.contribute.jzgloan.com/app/enterprise/client")
		if err != nil {
			return err
		}
		core.GetLogger().Info(string(res.Body()))
	}
	return nil
}

func (c *CustomerChannel) getClient() *resty.Request {
	return c.C.R()
}

func NewCustomerChannel() *CustomerChannel {
	return &CustomerChannel{C: resty.New()}
}
